package com.ruoyi.caiwu.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.caiwu.domain.*;
import com.ruoyi.caiwu.dto.*;
import com.ruoyi.caiwu.service.*;
import com.ruoyi.common.core.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @projectName: train-ruoyi-first
 * @package: com.ruoyi.caiwu.controller
 * @className: CaiwuController
 * @author: 刘乘滨
 * @description: TODO
 * @date: 2023/04/29 11:36
 * @version: 1.0
 */

@RestController
@RequestMapping("/caiwu")
public class CaiwuController {

    @Autowired
    CwCheckBatchService cwCheckBatchService;

    @Autowired
    CwPayOrderService cwPayOrderService;

    @Autowired
    CwCheckBatchDetailService cwCheckBatchDetailService;

    @Autowired
    CwClearingService cwClearingService;

    @Autowired
    CwCztxApplyService cwCztxApplyService;

    @Autowired
    CwDealPerDayService cwDealPerDayService;

    @Autowired
    CwReceiptPlanService cwReceiptPlanService;

    @Autowired
    CwPayOrderDetailService cwPayOrderDetailService;


    //对账列表查询
    @RequestMapping("/selectCheckBatch")
    public IPage<CwCheckBatch> selectCheckBatch(Page page, CwCheckBatchVo cwCheckBatchVo){

        return cwCheckBatchService.selectCheckBatch(page,cwCheckBatchVo);
    };

    //查询今日对账记录
    @RequestMapping("/getCwCheckBatchByBillDay")
    public CwCheckBatch getCwCheckBatchByBillDay(@RequestParam("date") String date){
        return cwCheckBatchService.getCwCheckBatchByBillDay(date);
    }

    //添加对账批次记录
    @RequestMapping("/addCwCheckBatch")
    public long addCwCheckBatch(@RequestBody CwCheckBatch cwCheckBatch){
        boolean save = cwCheckBatchService.save(cwCheckBatch);
        if(save){
            return cwCheckBatch.getId();
        }
        return 0;
    };

    //添加对账批次明细记录
    @RequestMapping("/addCwCheckBatchDetail")
    public void addCwCheckBatchDetail(@RequestBody CwCheckBatchDetail cwCheckBatchDetail){
        boolean save = cwCheckBatchDetailService.save(cwCheckBatchDetail);

    };

    //通过订单ID获取订单信息
    @RequestMapping("/getCwPayOrder")
    public CwPayOrder getCwPayOrder(@RequestParam("payOrderId")long payOrderId){
        return cwPayOrderService.selectById(payOrderId);
    }

    //对账确认
    @RequestMapping("/checkBatchConfirm")
    public Map<String,Object> checkBatchConfirm(String batchNo){
        HashMap<String, Object> map = new HashMap<>();
        try {
            CheckBatchConfirmRequestDto checkBatchConfirmRequestDto = new CheckBatchConfirmRequestDto();
            checkBatchConfirmRequestDto.setBatchNo(batchNo);
            cwCheckBatchService.checkBatchConfirm(checkBatchConfirmRequestDto);
            map.put("flag",true);
            return map;
        } catch (BusinessException ex) {
            map.put("flag",false);
            map.put("msg",ex.getDefaultMessage());
            return map;
        } catch (Exception e) {
            map.put("flag",false);
            map.put("msg",e.getMessage());
            return map;
        }
    }

    //交易流水查询（分页）
    @RequestMapping("/searchTradingFlow")
    public IPage<CwPayOrder> searchTradingFlow(Page page, CwPayOrderVo cwPayOrderVo){

        return cwPayOrderService.searchTradingFlow(page,cwPayOrderVo);
    }

    //交易流水查询
    @RequestMapping("/searchTradingFlows")
    public List<CwPayOrderDetail> searchTradingFlow(@RequestBody CwPayOrderVo vo){
        return cwPayOrderDetailService.searchTradingFlow(vo);
    }

    //对账明细查询
    @RequestMapping("/selectCheckBatchDetail")
    public List<CwCheckBatchDetail> selectCheckBatchDetail(@RequestBody CwCheckBatchDetailVo cwCheckBatchDetailVo){

        return cwCheckBatchDetailService.selectCheckBatchDetail(cwCheckBatchDetailVo);
    }

    @RequestMapping("/processCheckDifResult")
    public boolean processCheckDifResult(Long checkBatchDetailId, Integer processState){

        cwCheckBatchService.processCheckDifResult(checkBatchDetailId,processState);
        return true;
    }

    //对账批次查询
    @RequestMapping("/settlementManagement")
    public List<CwClearing> settlementManagement(String checkBatchNo){

        return cwClearingService.settlementManagement(checkBatchNo);
    }

    //确认结算
    @RequestMapping("/settlementManagementDispose")
    public boolean settlementManagementDispose(String add){
        List<Long> list = null;
        if(add != null){
            list = Arrays.asList(add.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
            cwClearingService.confirmClearing(list);
        }

        return true;
    }

    //营业报表查询
    @RequestMapping("/searchCwDealPerDayPage")
    public Map<String,Object> searchCwDealPerDayPage(Page page, CwDealPerDayVo vo){
        HashMap<String, Object> map = new HashMap<>();

        CwDealPerDayTotalDto cwDealPerDayTotalDto = null;

        IPage<CwDealPerDayDto> list = cwDealPerDayService.searchCwDealPerDayPage(page, vo);
        cwDealPerDayTotalDto = cwDealPerDayService.searchCwDealPerDaySum(vo);

        if(null == cwDealPerDayTotalDto){
            cwDealPerDayTotalDto = new CwDealPerDayTotalDto(
                    new BigDecimal(0),
                    new BigDecimal(0),
                    new BigDecimal(0),
                    new BigDecimal(0),
                    new BigDecimal(0),
                    new BigDecimal(0),
                    new BigDecimal(0),
                    new BigDecimal(0),
                    new BigDecimal(0));
        }

        if(null != list.getRecords()){
            String[][] a = new String[list.getRecords().size()][2];

            int i = 0;
            for (CwDealPerDayDto record : list.getRecords()) {
                String[] b = new String[2];
                String format = DateFormat.getDateInstance().format(record.getDealDate());
                b[0] = format;
                b[1] = record.getTotal()+"";
                a[i] = b;
                i ++;
            }

            map.put("opinionData",a);
        }

        map.put("dto",cwDealPerDayTotalDto);
        map.put("records",list.getRecords());
        map.put("total",list.getTotal());

        return map;
    }

    //收入明细查询
    @RequestMapping("/searchCwDealPerDayDetailReceiptPage")
    public Map<String,Object> searchCwDealPerDayDetailReceiptPage(CwDealPerDayVo vo){
        HashMap<String, Object> map = new HashMap<>();
        List<CwDealPerDayDetailReceiptDto> list = cwReceiptPlanService.searchCwDealPerDayDetailReceiptPage(vo);
        map.put("list",list);

        return map;
    };

    //支出明细查询
    @RequestMapping("/searchCwDealPerDayDetailPayPage")
    public List<CwDealPerDayDetailReceiptDto> searchCwDealPerDayDetailPayPage(CwDealPerDayVo vo){
        return cwReceiptPlanService.searchCwDealPerDayDetailPayPage(vo);
    }

    //收款计划列表查询
    @RequestMapping("/receiptManage")
    public Map<String,Object> receiptManage(Page page, RequestReceiptManageDto vo){
        return cwReceiptPlanService.receiptManage(page,vo);
    }

    //营业报表导出excel
    @RequestMapping("/cwDealPerDayExcelList")
    private boolean cwTradingFlowExcelList(Page page,CwDealPerDayVo vo) {

        List<CwDealPerDayDto> list = cwDealPerDayService.searchCwDealPerDayPage(page, vo).getRecords();

        String fileName = "";

        if(vo.getOperationType() == 1){
            fileName = "D:\\Excel\\"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"_营业收入报表.xlsx";
        }else if(vo.getOperationType() == 2){
            fileName = "D:\\Excel\\"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"_营业支出报表.xlsx";
        }

        EasyExcel.write(fileName, CwDealPerDayDto.class).sheet("营业报表").doWrite(list);

        return true;
    }
}
